import React, {Component, PropTypes} from 'react';
import {observer} from 'mobx-react'
import classNames from 'classnames'
import fetchJsonp from 'fetch-jsonp'
import {ActionSheet} from 'react-weui'
import '../styles/Search.css';
import Album from './Album'
import search from '../assets/icon-search.png'
import icon_music from '../assets/icon-music.png'
import black from '../assets/icon-...black.png'
import icon_album from '../assets/icon-album.png'
import icon_singer from '../assets/icon-singer.png'
import icon_mv from '../assets/icon-mv.png'
@observer
class Search extends Component {

  constructor(props) {
    super(props)
    this.search = this.search.bind(this)
    this.focus = this.focus.bind(this)
    this.searchCancel = this.searchCancel.bind(this)
    this.play = this.play.bind(this)
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
    this.showAlbum = this.showAlbum.bind(this)
    this.showSinger = this.showSinger.bind(this)
    this.handleKeyUp = this.handleKeyUp.bind(this)
    this.state = {
      searchShow: false,
      searchHistory: [],
      hotKey: [],
      key: '',
      searchRes: null,
      auto_show: false,
      menus: [{
        label: '拍照',
        onClick: () => {
        }
      }, {
        label: '从手机相册选择',
        onClick: () => {
        }
      }],
      actions: [
        {
          label: '取消',
          onClick: this.hideMenu
        }
      ],
      isAlbumShow: false,
      mid: 0,
    }
  }


  focus() {
    const {showRank} = this.props
    showRank(false)
    this.setState({
      searchShow: true
    })
  }

  searchCancel(e) {
    e.preventDefault()
    const {showRank} = this.props
    showRank(true)
    this.refs.input.blur()
    this.refs.input.value = ''
    this.setState({
      searchShow: false,
      searchRes: null,
      key: ''
    })
  }

  search(key) {
    this.setState({
      key: key
    })
    this.refs.input.value = key
    fetchJsonp(`http://c.y.qq.com/splcloud/fcgi-bin/smartbox_new.fcg?is_xml=0&format=jsonp&key=${key}&g_tk=5381&loginUin=0&hostUin=0&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0`, {
      jsonpCallback: 'jsonpCallback'
    }).then(res => res.json())
      .then(response => {
        this.setState({
          searchRes: response.data
        })
      })
  }

  play(index) {
    const {musicStore} = this.props;
    musicStore.play()
  }

  showMenu(index) {
    const {musicStore} = this.props
    this.setState({
      menus: [{
        label: '下一首播放',
        onClick: () => {
          musicStore.addToPlayListAsNextPlay(this.state.searchRes.song.itemlist[index])
          this.hideMenu()
        }
      }, {
        label: '添加到播放列表',
        onClick: () => {
          musicStore.addToPlayList(this.state.searchRes.song.itemlist[index])
          this.hideMenu()
        }
      }],
      auto_show: true
    })
  }

  hideMenu() {
    this.setState({
      auto_show: false
    })
  }

  showAlbum(mid) {
    this.setState({
      mid: mid,
      isAlbumShow: true
    })
  }

  showSinger() {

  }

  componentDidMount() {
    if (localStorage.searchHistory) {
      this.setState({
        searchHistory: JSON.parse(localStorage.searchHistory)
      })
    }
    fetchJsonp('http://c.y.qq.com/splcloud/fcgi-bin/gethotkey.fcg?g_tk=5381&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0', {
      jsonpCallback: 'jsonpCallback'
    }).then(res => res.json())
      .then(response => {
        this.setState({
          hotKey: response.data.hotkey.slice(0, 5)
        })
      })
  }

  handleKeyUp(e) {
    if (e.keyCode === 13) {
      this.search(this.refs.input.value)
    }
  }

  render() {
    const {musicStore} = this.props
    return (
      <div id="search">
        <ActionSheet
          menus={this.state.menus}
          actions={this.state.actions}
          show={this.state.auto_show}
          type="ios"
          onRequestClose={e => this.setState({ios_show: false})}
        />
        <div className="search">
          <div className="search-input">
            <img src={search} alt="搜索" onClick={() => (this.search(this.refs.input.value))}/>
            <form>
              <input type="text" ref="input"
                     placeholder="搜索 歌曲/专辑/歌手"
                     onKeyUp={this.handleKeyUp}
                     onFocus={() => (this.focus())}/>
            </form>
          </div>
          <div className={classNames('search-cancel', {'search-cancel-show': this.state.searchShow})}
               onTouchEnd={this.searchCancel}
               onClick={this.searchCancel}>
            取消
          </div>
        </div>
        {
          (!this.state.searchRes && this.state.searchShow) &&

          <div className="hotkey">
            <div className="search-history">
              {
                this.state.searchHistory.map(item => (
                  <div className="search-history-item" key={item} onClick={this.search(item)}>{item}</div>
                ))
              }
            </div>
            <ul>
              {
                this.state.hotKey.map((item, index) => (
                  <li key={index} onClick={() => {
                    this.search(item.k)
                  }}>
                    <span className="hotkey-index">{index + 1}</span>
                    <span className="hotkey-k">{item.k}</span>
                    <span className="hotkey-n">{Math.round(item.n / 1000) / 10 + '万'}</span>
                  </li>
                ))
              }

            </ul>
          </div>
        }

        {

          (this.state.searchRes && this.state.searchShow) &&

          <div className="result">
            {
              this.state.searchRes.song != null &&

              <div className="result-group">
                <div className="group">
                  <img className="group-img" src={icon_music} role="presentation"/>
                  <p className="group-p">单曲</p>
                </div>
                {
                  this.state.searchRes.song.itemlist.map((item, index) => (
                    <div className="result-item" key={index}>
                      <p className="result-title">{item.name}</p>
                      <p className="result-author">-{item.singer}</p>
                      <div className="action-button" onTouchEnd={(e) => {
                        e.preventDefault();
                        this.showMenu(index)
                      }} onClick={() => {
                        this.showMenu(index)
                      }}>
                        <img src={black} role="presentation"/>
                      </div>
                    </div>
                  ))
                }
              </div>
            }
            {
              this.state.searchRes.album != null &&

              <div className="result-group">
                <div className="group">
                  <img className="group-img" src={icon_album} role="presentation"/>
                  <p className="group-p">专辑</p>
                </div>
                {
                  this.state.searchRes.album.itemlist.map(item => (
                    <div className="album-item" onClick={() => {
                      this.showAlbum(item.mid)
                    }} key={item.mid}>
                      <img className="album-img" src={item.pic} role="presentation"/>
                      <div className="album-info">
                        <p className="album-name">{item.name}</p>
                        <p className="album-author">{item.singer}</p>
                      </div>
                    </div>
                  ))
                }
              </div>
            }

            {
              this.state.searchRes.singer != null &&
              <div className="result-group">
                <div className="group">
                  <img className="group-img" src={icon_singer} role="presentation"/>
                  <p className="group-p">歌手</p>
                </div>
                {

                  this.state.searchRes.singer.itemlist.map(item => (
                    <div className="singer-item" onClick={() => {
                      this.showSinger(item.mid)
                    }} key={item.mid}>
                      <img className="singer-img" src={item.pic} role="presentation"/>
                      <div className="singer-p">
                        <p>{item.name}</p>
                      </div>
                    </div>
                  ))
                }
              </div>
            }
            {
              this.state.searchRes.mv != null &&
              <div className="result-group">
                <div className="group">
                  <img className="group-img" src={icon_mv} role="presentation"/>
                  <p className="group-p">MV</p>
                </div>
                {
                  this.state.searchRes.mv.itemlist.map(item => (
                    <div className="mv-item" key={item.name}>
                      <p className="mv-name">{item.name}</p>
                      <p className="mv-author">{item.singer}</p>
                    </div>
                  ))
                }
              </div>
            }
          </div>
        }
        {
          this.state.isAlbumShow && <Album mid={this.state.mid} musicStore={musicStore}/>
        }
      </div>
    );
  }
}

Search.propTypes = {
  showRank: PropTypes.func.isRequired,
  musicStore: PropTypes.object.isRequired,
}

export default Search;
